package org.truenewx.tnxjee.core.enums;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.truenewx.tnxjee.core.Strings;

/**
 * 枚举类型标识，可唯一标识一个枚举类型
 *
 * @author jianglei
 */
public class EnumTypeIdentity {

    /**
     * 分隔符，默认为-，以使得字符串形式可作为DOM元素的id属性值
     */
    public static final String SEPARATOR = Strings.MINUS;

    /**
     * 名称
     */
    private String name;
    /**
     * 子名称
     */
    private String subname;

    public EnumTypeIdentity() {
    }

    public EnumTypeIdentity(String name, String subname) {
        this.name = name;
        this.subname = subname;
    }

    public String getName() {
        return this.name;
    }

    protected void setName(String name) {
        if (name != null) {
            Assert.isTrue(!name.contains(SEPARATOR), "The name cannot contain '" + SEPARATOR + "'");
        }
        this.name = name;
    }

    public String getSubname() {
        return this.subname;
    }

    protected void setSubname(String subname) {
        if (subname != null) {
            Assert.isTrue(!subname.contains(SEPARATOR), "The subname cannot contain '" + SEPARATOR + "'");
        }
        this.subname = subname;
    }

    public boolean matches(String name, String subname) {
        return StringUtils.equals(this.name, name) && StringUtils.equals(this.subname, subname);
    }

    @Override
    public String toString() {
        return toString(this.name, this.subname);
    }

    public static String toString(String name, String subname) {
        String s = name;
        if (StringUtils.isNotBlank(subname)) {
            s += SEPARATOR + subname;
        }
        return s;
    }

    public static EnumTypeIdentity of(String key) {
        EnumTypeIdentity identity = new EnumTypeIdentity();
        int index = key.indexOf(SEPARATOR);
        if (index > 0) {
            identity.setName(key.substring(0, index));
            identity.setSubname(key.substring(index + SEPARATOR.length()));
        } else {
            identity.setName(key);
        }
        return identity;
    }

}
